package CelestialWorkflow;

import CelestialDataAccess.User;
import CelestialDataAccess.*;

public class LoginControl {

    public static final int NULL_EMAIL = 1;         // no email supplied
    public static final int NULL_PWD = 2;           // no password supplied
    public static final int EMAIL_NT_REG = 3;     // no records found
    public static final int WRONG_PWD = 4;          // password mismatch
    public static final int INVALID_EMAIL = 5;      // email syntax is worng
    public static final int INACTIVE_ACC = 6;       // inactive account
    public static final int SYS_ERR = 7;            // system error, see message
    
    private int m_iError = 0;
    private String m_strErrorMessage = "";
    /*************************************************************************/
    /* get/set methods */
    public int getError(){ return m_iError; }
    public String getErrorMessage(){ return m_strErrorMessage; }
    /*************************************************************************/
    /* constructors */
    public LoginControl(){}

    /*************************************************************************/
    /* client methods */
    public User validateLogin(String email, String password){

        /* clear error message */
        m_iError = 0;
        m_strErrorMessage = "";

        /* check for nulls */
        if(email.length()==0){
                m_iError = NULL_EMAIL;
                return null;
        }
        if(password.length()==0){
                m_iError = NULL_PWD;
                return null;
        }
        /* begin validate against database*/
        try {
            /* retrieve customer data */
            UsersDataAccess daUsers = new UsersDataAccess();
            User usr = daUsers.validateLogin(email, password);
            boolean bEmailExists = daUsers.isEmailRegistered(email);
            boolean bAccountActive = daUsers.isAccountActive(email);
            
            if(usr==null){
                if(bEmailExists){
                   if(!bAccountActive) m_iError = INACTIVE_ACC; 
                   else m_iError = WRONG_PWD;
                }
                else if(!Validation.validateEmail(email))
                   m_iError = INVALID_EMAIL;
                else
                   m_iError = EMAIL_NT_REG;
            }
            return usr;
        }
        catch (DataAccessException ex1){
            m_iError = SYS_ERR;
            m_strErrorMessage = ex1.getMessage();
            return null;
        }
    }
    /*************************************************************************/
    /* test */
    public static void main(String[] args){

        LoginControl lgctrl = new LoginControl();
        User usr = lgctrl.validateLogin("chseng@homecodeworks.com", "1123581321");

        if(usr!=null)
            System.out.println(usr);
        else    
            System.out.println(lgctrl.getError());
    }
}
